import logging
from urllib2 import *

import urllib

from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from pylons.decorators import jsonify

from solrmedia.lib.base import BaseController, render

log = logging.getLogger(__name__)

class SearchController(BaseController):

    @jsonify
    def index(self):
        query = ''
        facet = ''
        page = 1
        debug = False

        search_results = []
        facets = []

        url = 'http://localhost:8983/solr/select'
        data = self.__build_query(query, facet, page)

        response = eval(urllib.urlopen(url, data).read())
	
        if response["facet_counts"]['facet_fields']:
            facets = response["facet_counts"]['facet_fields']

        if debug:
            debug_info = url + '?' + data
        else:
            debug_info = None

        return {
            'query' : query,
            'total_results_found' : response["response"]["numFound"],
            'search_results' : response["response"]["docs"],
            'facets' : facets,
            'debug_info' : debug_info
		}
        
        # Return a rendered template
        #return render('/search.mako')
        # or, return a string
        return 'Hello World'
        
    def __build_query(self, query, facet, page):
        if query == '':
            q = '*:*'  # '*'
            facet_mincount = 0
        else:
            q = 'title:%s OR author:%s OR genre:%s' % (query, query, query)
            facet_mincount = 1

        page = (int(page) -1) * 100

        return urllib.urlencode([
            ('q', q),
            ('wt', 'python'),
            ('facet', 'true'),
            ('facet.field', 'genre'),
            ('facet.field', 'performer'),
            ('facet.mincount', facet_mincount),
            ('fq', facet),
            ('start', page),
            ('rows', '100')
        ])
